<?php
namespace App\GraphQL\Mutations\DeviceOrder;

use App\Models\DeviceOrder;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use Illuminate\Support\Carbon;
use App\Models\User;
use App\Models\FactoryStatistical;
use Illuminate\Support\Facades\DB;

class Pay
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        DB::transaction(function () use ($args) {
            $data = $args['input'];
            $id = $args['id'];
            $deviceOrder = $this->validate($id, $data);
            $data['payment_time'] = Carbon::now();
            $data['original_price'] = $data['original_price'] * 100;
            $data['discount_price'] = $data['discount_price'] * 100;
            $data['cost_total_price'] = $data['cost_total_price'] * 100;
            $data['before_profit'] = $data['before_profit'] * 100;
            $data['after_profit'] = $data['after_profit'] * 100;
            $data['status'] = 'WAIT_DELIVERY';
            $data['pay_user_id'] = auth()->user()->id;
            $deviceOrder->update($data);
            $factoryStatistical = FactoryStatistical::firstOrCreate([
                'user_id' => $deviceOrder->factory_user_id
            ]);
            // 增加厂家订单统计
            $factoryStatistical->increment('total_order');
        });
        return [
            'status' => '200',
            'message' => '付款成功'
        ];
    }

    public function validate($id, $data)
    {
        $rules = [
            'transfer_voucher' => [
                'required'
            ],
            'original_price' => [
                'required',
                'min:1'
            ],
            'discount_price' => [
                'required',
                'min:1'
            ],
            'cost_total_price' => [
                'required',
                'min:1'
            ],
            'before_profit' => [
                'required',
                'min:0',
                'max:100'
            ],
            'after_profit' => [
                'required',
                'min:0',
                'max:100'
            ],
            'factory_user_id' => [
                'required'
            ]
        ];
        $messages = [
            'transfer_voucher.required' => '转账不能为空',
            'original_price.required' => '设备原价不能为空',
            'discount_price.required' => '设备折扣价不能为空',
            'cost_total_price.required' => '设备成本价不能为空',
            'before_profit.required' => '盈利前分成比例不能为空',
            'after_profit.required' => '盈利后分成比例不能为空',
            'factory_user_id.required' => '厂家不能为空',
            'original_price.min' => '原价不能小于1',
            'discount_price.min' => '折扣价不能小于1',
            'cost_total_price.min' => '成本价不能小于1',
            'before_profit.min' => '盈利前为最小为1',
            'after_profit.min' => '盈利后为最小为1',
            'before_profit.max' => '盈利前为最大为100',
            'after_profit.max' => '盈利后为最大为100'
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        $old = DeviceOrder::find($id);
        if (! $old) {
            throw new \Exception('订单不存在!');
        }
        if ($old->status !== 'WAIT_PAY') {
            throw new \Exception('订单已经支付,无法重复操作!');
        }
        $factory = User::find($data['factory_user_id']);
        if (! $factory || $factory->role_code !== 'FACTORY') {
            throw new \Exception('厂家不存在!');
        }
        return $old;
    }
}
